package cn.leida.ruoyi.client.util;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.leida.base.git.config.AppGitCfg;
import cn.leida.common.json.util.JsonPathUtil;
import cn.leida.ruoyi.client.types.ClientDataType;
import cn.leida.ruoyi.common.core.domain.entity.SysMenu;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @author lei
 * @create 2025-03-12 22:25
 */
public class ClientMenuUtil {

    public static List<JSONObject> cleanSysMenuList(List<SysMenu> menus) {
        List<JSONObject> jsonList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(menus)) {
            for (SysMenu menu : menus) {
                JSONObject json = JSONObject.from(menu);
                json.remove("params");
                json.remove("children");
                jsonList.add(json);
            }
        }
        return jsonList;
    }


    public static void saveJsonFile(List<SysMenu> menus, File jsonFile) {
        // 查询角色的所有菜单
        List<JSONObject> jsonList = ClientMenuUtil.cleanSysMenuList(menus);
        // 保存到json文件
        FileUtil.writeUtf8String(JSONObject.toJSONString(jsonList, JSONWriter.Feature.PrettyFormat), jsonFile);
    }

    /**
     * 加载菜单
     */
    public static List<SysMenu> loadSysMenuList() {
        List<SysMenu> menus = new ArrayList<>();
        File jsonFile = AppGitCfg.clientMenuJsonFile();
        List<JSONObject> dataList = JsonPathUtil.listJSONObject(jsonFile);
        for (JSONObject json : dataList) {
            menus.add(json.toJavaObject(SysMenu.class));
        }
        return menus;
    }


}
